﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SP.SPProjects.WebParts.Support;
using SP.SPProject.Core.Support;
using SP.SPProjects.WebParts.Model;
using Microsoft.SharePoint;

namespace SP.SPProjects.WebParts.Presentation
{
    public class ListTasksPresenter : Presenter<IListTasksView>, IListTasksPresenter
    {

        #region Properties

        DataAccess<DataContext, TasksBaseTask> _da;

        #endregion

        #region Constructors

        public ListTasksPresenter(IListTasksView view)
            : base(view)
        {
            _da = new DataAccess<DataContext, TasksBaseTask>("Tasks");
        }

        #endregion

        public void HandleLoad()
        {
            View.UserTasks = _da.GetFiltered(c => c.AssignedToId.Equals(SPContext.Current.Web.CurrentUser.ID));
            View.Show();
        }

        public void HandleStartStopCounter()
        {
            var task = _da.GetFiltered(c => c.Id.Equals(View.TaskId)).FirstOrDefault();
            if (!task.TaskRunning.HasValue || !task.TaskRunning.Value)
                startCounter(task);
            else
                stopCounter(task);
        }

        private void startCounter(TasksBaseTask task)
        {
            task.TaskRunning = new bool?(true);
            task.StartRealTime = DateTime.Now;
            _da.Update(task);
        }

        private void stopCounter(TasksBaseTask task)
        {
            task.TaskRunning = new bool?(false);
            task.ConsumedTime = View.ElapsedTime;
            _da.Update(task);
        }

    }
}
